<?php
//定时确认收货
namespace app\api\command;

use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\Db;
use app\common\controller\Commission;
use think\Log;

class OrderConfirm extends Command
{
    protected function configure()
    {
        $this->setName('order_confirm');
    }

    //所有自提订单没有自动确认收货
    protected function execute(Input $input, Output $output)
    {
        //所有待收货的快递类型订单
        $waitOrder = db('order')->where(['order_status'=>'3'])->where('door_type','2')->select();
        $takeDay = db('config')->where(['name'=>'success_day','group'=>'basic'])->value('value');//用户下单
        $takeCaiDay = db('config')->where(['name'=>'success_day_cai','group'=>'basic'])->value('value');//采购

        foreach ($waitOrder AS $key => $value) {
            $useTakeDay = $takeCaiDay;
            if (in_array($value['order_type'],[1,2])) {
                $useTakeDay = $takeDay;
            }
            $useTakeDay = $useTakeDay*86400;
            $cha = time()-$value['addtime'];
            if ($cha >= $useTakeDay) {
                $orderInfo = $value;
                if (in_array($value['order_type'],[1,2])) {
                    //普通订单
                    $this->confirm($orderInfo);
                }
                if (in_array($value['order_type'],[4,5])) {
                    //采购订单
                    $this->confirmCai($orderInfo);
                }
            }
        }
        exit('订单确认收货脚本执行完成');
    }

    //普通订单确认收货
    public function confirm($orderInfo)
    {
        Db::startTrans();
        try {
            $userId = $orderInfo['user_id'];
            $storeId = $orderInfo['store_id'];
            $orderId = $orderInfo['id'];

            if (empty($orderInfo)) {
                return false;
            }
            if (in_array($orderInfo['order_status'], [0,1,2,4,5])) {
                return false;
            }

            /**********更新订单状态**********/
            db('order')->where(['user_id' => $userId, 'id' => $orderId])->update([
                'order_status' => 4,
                'order_qr_time' => time(),
                'ti_code'=>0
            ]);

            /***升级高级用户操作***/
            $user = db('user')->where('id',$userId)->find();
            if ($user['type'] == 1) {
                $buyNum = db('config')->where(['name'=>'highuser_count','group'=>'basic'])->value('value');
                $buyPrice = db('config')->where(['name'=>'highuser_price','group'=>'basic'])->value('value');
                $userAllPrice = db('order')->where(['user_id'=>$userId])->where('order_status','4')->sum('price');
                $orderGoodsNum = db('order')->alias('a')->join('order_goods b','a.id=b.order_id','left')->where(['a.user_id'=>$userId])->where('a.order_status','4')->sum('num');
                if ($orderGoodsNum >= $buyNum || $userAllPrice >= $buyPrice) {
                    db('user')->where('id',$userId)->update([
                        'type'=>2
                    ]);
                }
            }

            /********下单送积分*********/
            $userScoreRatio = db('integral_score_rule')->where('type','4')->value('ratio');
            $userScoreRatio = $userScoreRatio ? $userScoreRatio : 0;
            $sendScore = round($orderInfo['price']*($userScoreRatio/100));
            if ($sendScore > 0) {
                $uLockInfo = db('user')->where('id',$userId)->lock(true)->find();
                db('user')->where('id',$userId)->setInc('integral',$sendScore);
                $gDay = db('integral_score_rule')->where('type',5)->value('day');
                $guoQi = strtotime(date('Y-m-d'))+86400+$gDay*86400;
                db('integral_change_log')->insert([
                    'user_id'=>$userId,
                    'store_id'=>$storeId,
                    'scene'=>4,
                    'score'=>$sendScore,
                    'total_score'=>$uLockInfo['integral']+$sendScore,
                    'residue_score'=>$sendScore,
                    'type'=>2,
                    'order_id'=>$orderId,
                    'exptime'=>date('Y-m-d H:i:s',$guoQi),
                    'addtime'=>date('Y-m-d H:i:s'),
                ]);
            }
            

            /*******发放各种佣金*********/
            $orderGoods = db('order_goods')->where('order_id', $orderId)->select();

            $fxPrice = 0;//一级分销佣金
            $fxPriceTwo = 0;//二级分销佣金
            $pUserId = 0;//分销人用户id
            $pUserIdTwo = 0;//二级分销用户id
            $rate = 0;
            $rateTwo = 0;

            foreach ($orderGoods AS $key => $value) {
                $goodsStore = db('order_goods_store')->where(['order_id' => $orderId, 'order_goods_id' => $value['id']])->select();
                foreach ($goodsStore AS $k => $v) {
                    $fxPrice += $v['fx_price'];
                    $fxPriceTwo += $v['fx_pricetwo'];
                    $pUserId = $v['p_user_id'];
                    $pUserIdTwo = $v['p_user_idtwo'];
                    $rate = $v['fx_rate'];
                    $rateTwo = $v['fx_ratetwo'];
                }
                //更新商品销量
                db('goods')->where('id',$value['goods_id'])->setInc('salecount',$value['num']);
            }

            //1=采购发放,2=核销发送
            $promotionRule = db('promotion_rule')->limit(0, 1)->value('promotion_status');
            if ($promotionRule == 2) {
                $commissionServices = new Commission();
                //业务员佣金
                $yeWuPrice = $commissionServices->yeWuPrice($orderId,$storeId);
                if ($yeWuPrice == false) {
                    Db::rollback();
                    return false;
                }
                //推广佣金发放
                $resultPromotion = $commissionServices->promotionPrice($orderId,$storeId);
                if ($resultPromotion == false) {
                    Db::rollback();
                    return false;
                }
                //更新order_goods_store发放状态
                db('order_goods_store')->where(['order_id'=>$orderId])->update([
                    'isfa' => 1,
                    'fa_time'=>time(),
                    'successtime'=>time()
                ]);
            } else {
                db('order_goods_store')->where(['order_id'=>$orderId])->update([
                    'successtime'=>time()
                ]);
            }
            //分销佣金
            if (!empty($pUserId) && in_array($user['type'],[1,2])) {
                $user11 = db('user')->where('id',$pUserId)->find();
                $type = $user11['type'];
                if ($type == 2) {
                    $type = 1;
                }
                if ($type == 3) {
                    $type = 2;
                }

                //合伙人未首次缴费，未储值
                if ($user11['is_card_pay'] == 0 && $user11['type'] == 3) {

                } else {
                    db('fenxiao_log')->insert([
                        'user_id'=>$pUserId,
                        'to_user_id'=>$userId,
                        'order_price'=>$orderInfo['price'],
                        'order_id'=>$orderId,
                        'price'=>$fxPrice,
                        'store_id'=>$orderInfo['store_id'],
                        'rate'=>$rate,
                        'type'=>$type,
                        'addtime'=>time()
                    ]);

                    //更新账户余额
                    db('user')->where('id',$pUserId)->lock(true)->find();
                    db('user')->where('id',$pUserId)->setInc('commission_money',$fxPrice);
                }

                if (!empty($pUserIdTwo)) {
                    $user22 = db('user')->where('id',$pUserIdTwo)->find();
                    $type1 = $user22['type'];
                    if ($type1 == 2) {
                        $type1 = 1;
                    }
                    if ($type1 == 3) {
                        $type1 = 2;
                    }
                    //合伙人未首次缴费，未储值
                    if ($user22['is_card_pay'] == 0 && $user11['type'] == 3) {

                    } else {
                        db('fenxiao_log')->insert([
                            'user_id'=>$pUserIdTwo,
                            'to_user_id'=>$userId,
                            'order_price'=>$orderInfo['price'],
                            'order_id'=>$orderId,
                            'price'=>$fxPriceTwo,
                            'store_id'=>$orderInfo['store_id'],
                            'rate'=>$rateTwo,
                            'type'=>$type1,
                            'addtime'=>time()
                        ]);
                        //更新账户余额
                        db('user')->where('id',$pUserIdTwo)->lock(true)->find();
                        db('user')->where('id',$pUserIdTwo)->setInc('commission_money',$fxPriceTwo);
                    }
                }
            }
            Db::commit();
            return true;
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            return false;
            $this->error($e->getMessage());
        }
    }

    //采购订单确认收货
    public function confirmCai($orderInfo)
    {
        $storeId = $orderInfo['store_id'];
        $orderId = $orderInfo['id'];
        $store = db('store')->where('id', $storeId)->find();
        if (empty($orderInfo)) {
            return false;
        }
        if (in_array($orderInfo['order_status'], [0,1,2,4,5])) {
            return false;
        }
        $orderReturn = db('order_return')->where('order_id',$orderId)->where('refund_status',1)->find();
        if (!empty($orderReturn)) {
            return false;
        }

        Db::startTrans();
        try {
            /**********更新订单状态**********/
            db('order')->where(['id' => $orderId])->update([
                'order_status' => 4,
                'order_qr_time' => time(),
                'ti_code'=>0
            ]);

            //退货的产品和数量
            $returnGoods = [];
            $orderReturn = db('order_return')->where('order_id',$orderId)->where('refund_status',2)->select();
            if (!empty($orderReturn)) {
                foreach ($orderReturn AS $okey => $ov) {
                    $orderReturnGoods = db('order_return_goods')->where('return_id',$ov['id'])->select();
                    foreach ($orderReturnGoods AS $rkey => $rv) {
                        $returnGoods[$rv['goods_id']] = $rv['refund_num'];
                    }
                }
            }

            $orderGoods = db('order_goods')->where('order_id', $orderId)->select();
            foreach ($orderGoods AS $key => $value) {
                $goodsId = $value['goods_id'];
                $goodsNum = $value['num'];
                //增加空间/中心库存
                if (isset($returnGoods[$goodsId])) {
                    $goodsNum-=$returnGoods[$goodsId];
                }

                $storeGoods = db('store_goods')->where(['store_id'=>$storeId,'goods_id'=>$goodsId])->find();
                if (empty($storeGoods)) {
                    $goodss = db('goods')->where('id',$goodsId)->find();
                    db('store_goods')->insert([
                        'store_id'=>$storeId,
                        'goods_id'=>$goodsId,
                        'cate_id' =>$goodss['cate_id'],
                        'cate_id2'=>$goodss['cate_id2'],
                        'real_stock'=>$goodsNum,
                        'stock'=>$goodsNum,
                        'addtime'=>time()
                    ]);
                } else {

                    $storeGoodsId = db('store_goods')->where(['store_id'=>$storeId,'goods_id'=>$goodsId])->value('id');
                    db('store_goods')->where('id',$storeGoodsId)->lock(true)->find();
    
                    db('store_goods')->where('id',$storeGoodsId)->inc('stock',$goodsNum)->inc('real_stock',$goodsNum)->update();
                }
            }

            $promotionRule = db('promotion_rule')->limit(0, 1)->value('promotion_status');
            //1=采购发放,2=核销发送  判断发放佣金的模式，核销模式才发
            if ($promotionRule == 1) {
                $commissionServices = new Commission();
                //业务佣金发放
                $resultYewu = $commissionServices->yeWuPrice($orderId,$storeId);
                if ($resultYewu == false) {
                    Db::rollback();
                    return false;
                }
                //推广佣金发放
                $resultPromotion = $commissionServices->promotionPrice($orderId,$storeId);
                if ($resultPromotion == false) {
                    Db::rollback();
                    return false;
                }
                //更新order_goods_store发放状态
                db('order_goods_store')->where(['cai_order_id'=>$orderId])->update([
                    'isfa' => 1,
                    'fa_time'=>time(),
                    'cai_successtime'=>time()
                ]);
            } else {
                db('order_goods_store')->where(['cai_order_id'=>$orderId])->update([
                    'cai_successtime'=>time()
                ]);
            }
            Db::commit();
            return true;
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            return false;
            $this->error($e->getMessage());
        }
    }
}
